'use strict';

const Controller = require('egg').Controller;
const SELECT = require('../../../../config/select');
class TagController extends Controller {
    /**
     * 获取标签
     */
    async find() {
        const { ctx } = this;
        let { id, name, page, currentPage } = ctx.query;
        const select = SELECT.TAG;
        const Rules = {
            id: {
                type: 'objectId',
                required: false
            }
        };
        ctx.proving(Rules, ctx.query);

        if (name) {
            name = name.trimAll();
        }

        const tag = await ctx.service.tag.find({ id, name, page, currentPage }, select);

        ctx.success(tag);
    }

    /**
     * 修改标签
     */
    async update() {
        const { ctx } = this;
        const body = ctx.request.body;
        const name = body.name;
        const id = body.id;
        const desc = body.desc;

        const Rules = {
            name: {
                type: 'string',
                keyname: '标签名称'
            },
            id: {
                type: 'objectId',
                keyname: 'ID'
            }
        };

        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const tag = await ctx.service.tag.update(id, { name, desc });
        ctx.success({
            message: '修改成功'
        });
    }

    /**
     * 新增标签
     */
    async create() {
        const { ctx } = this;
        const body = ctx.request.body;
        const name = body.name;
        const desc = body.desc;

        const Rules = {
            name: {
                type: 'string',
                keyname: '标签名称'
            }
        };
        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const tag = await ctx.service.tag.create(name, desc);
        ctx.success({ id: tag.id });
    }

    /*
    * 删除标签
    * */
    async destroy() {
        const { ctx } = this;
        const id = ctx.query.id;
        console.log(ctx.query)

        const Rules = {
            id: {
                type: 'objectId',
                keyname: 'ID'
            }
        };
        ctx.proving(Rules, ctx.query);
        // 角色权限认证
        await ctx.powerValidate();

        // 检查此标签下是否存有文章 todo
        // const article = await ctx.service.article.find({ tag: id });
        // if (article.length > 0) {
        //     ctx.throw(402, '此标签下存在其他文章，无法删除');
        // }
        await ctx.service.tag.destroy(id);
        ctx.success({
            message: '删除成功'
        });
    }
}

module.exports = TagController;
